package com.gobang.controller;

import com.gobang.common.util.AuthContextHolder;
import com.gobang.domain.dto.SurrenderRequestDTO;
import com.gobang.domain.message.GameStateUpdateMessage;
import com.gobang.domain.vo.GameRoomVO;
import com.gobang.domain.vo.Result;
import com.gobang.domain.vo.SurrenderResponseVO;
import com.gobang.service.GameRoomService;
import com.gobang.service.NewGameService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 游戏管理控制器
 * 处理游戏相关的HTTP请求
 * 
 * @author System
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/game")
@RequiredArgsConstructor
public class GameController {

    private static final Logger log = LoggerFactory.getLogger(GameController.class);

    private final NewGameService gameService;
    private final GameRoomService gameRoomService;


    /**
     * 查询游戏房间信息
     *
     * @param roomId 房间ID
     * @return 房间信息
     */
    @GetMapping("/room/{roomId}")
    public Result<GameRoomVO> getRoomInfo(@PathVariable String roomId) {
        log.info("查询游戏房间信息，roomId: {}", roomId);
        
        try {
            // 获取当前用户ID
            Long userId = AuthContextHolder.getCurrentUserId();
            
            // 查询房间信息
            GameRoomVO roomInfo = gameService.getRoomInfo(roomId, userId);
            
            log.info("游戏房间信息查询成功，roomId: {}, userId: {}", roomId, userId);
            return Result.success(roomInfo, "查询成功");
            
        } catch (Exception e) {
            log.error("查询游戏房间信息失败，roomId: {}", roomId, e);
            return Result.error("QUERY_FAILED", "查询房间信息失败：" + e.getMessage());
        }
    }

    /**
     * 认输接口
     *
     * @param request 认输请求
     * @return 认输结果
     */
    @PostMapping("/surrender")
    public Result<SurrenderResponseVO> surrender(@Valid @RequestBody SurrenderRequestDTO request) {
        log.info("用户认输，request: {}", request);
        
        try {
            // 获取当前用户ID
            Long userId = AuthContextHolder.getCurrentUserId();
            request.setUserId(userId);
            
            // 处理认输
            SurrenderResponseVO response = gameRoomService.surrender(request);
            
            if (response.getSuccess()) {
                log.info("认输处理完成，userId: {}, roomId: {}", userId, request.getRoomId());
                return Result.success(response, "认输成功");
            } else {
                log.warn("认输处理失败，userId: {}, roomId: {}, error: {}", 
                    userId, request.getRoomId(), response.getErrorMessage());
                return Result.error("SURRENDER_FAILED", response.getErrorMessage());
            }
            
        } catch (Exception e) {
            log.error("认输处理异常，request: {}", request, e);
            return Result.error("SURRENDER_ERROR", "认输处理失败：" + e.getMessage());
        }
    }

    /**
     * 获取游戏状态（用于调试）
     *
     * @param roomId 房间ID
     * @return 游戏状态
     */
    @GetMapping("/state/{roomId}")
    public Result<GameStateUpdateMessage> getGameState(@PathVariable String roomId) {
        log.debug("获取游戏状态，roomId: {}", roomId);
        
        try {
            // 获取当前用户ID
            Long userId = AuthContextHolder.getCurrentUserId();
            
            // 获取游戏状态
            GameStateUpdateMessage gameState = gameService.getGameState(roomId, userId);
            
            log.debug("游戏状态获取成功，roomId: {}, userId: {}", roomId, userId);
            return Result.success(gameState, "获取成功");
            
        } catch (Exception e) {
            log.error("获取游戏状态失败，roomId: {}", roomId, e);
            return Result.error("STATE_QUERY_FAILED", "获取游戏状态失败：" + e.getMessage());
        }
    }
} 